<template>
  <div class="chat-container">
    <!-- 左侧用户列表 -->
    <div class="left-side">
      <!-- 搜索框 -->
      <div class="search-wrapper">
        <el-input
          v-model="searchUserName"
          placeholder="回车搜索用户"
          class="search-input"
          @keydown.enter.native="searchUserForForm"
        >
          <i slot="suffix" class="el-icon-search"></i>
        </el-input>
      </div>

      <!-- 用户列表 -->
      <el-scrollbar class="user-list-scroll">
        <el-row v-if="messageForm.length > 0">
          <el-col
            v-for="form in messageForm"
            :key="form.id"
            @click.native="chooseUser(form)"
            :class="['user-item', form.id === currentUser?.id ? 'active' : '']"
          >
            <div class="user-avatar-wrapper">
              <div
                :class="{ 'online-dot': form.otherUserId in onlineUsers }"
              ></div>
              <!-- 未读消息徽章 -->
              <el-badge
                :value="form.unreadCountUser2"
                class="message-badge"
                v-if="form.unreadCountUser2 > 0"
              >
                <img :src="form.otherUserAvatar" class="user-avatar" />
              </el-badge>
              <img v-else :src="form.otherUserAvatar" class="user-avatar" />
            </div>

            <div class="user-details">
              <div style="color: #565656" class="user-name">
                {{ form.otherUserName }}
              </div>
              <!-- <div class="user-name">{{ form.otherUserName }}</div> -->
              <div class="user-last-message">
                {{ form.lastMessageContent }}&nbsp;
              </div>
              <div class="user-last-time">
                {{ getTimePart(form.lastMessageTime) }}&nbsp;
              </div>
              <div class="user-status">{{ form.status }}</div>
            </div>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <div v-else class="no-users">
          <i class="el-icon-chat-dot-round"></i>
          <p>暂无用户</p>
        </div>
      </el-scrollbar>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="right-side">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <span v-if="currentUser">{{ currentUser.otherUserName }}</span>
        <span v-else>请选择会话开始聊天</span>
      </div>

      <!-- 消息区域 -->
      <el-scrollbar class="chat-messages" ref="messageContainer">
        <div class="messages-wrapper" v-if="currentUser">
          <div
            v-for="message in messages"
            :key="message.id"
            class="message-box"
            :class="{
              'own-message': message.senderId === loginUser.userId,
              'other-message': message.senderId !== loginUser.userId,
            }"
          >
            <!-- 头像 -->
            <div class="avatar">
              <img
                :src="
                  message.senderId === loginUser.userId
                    ? loginUser.avatar
                    : currentUser?.otherUserAvatar
                "
                alt="用户头像"
                @click="PushUserProfile()"
              />
            </div>

            <!-- 消息内容 -->
            <div class="message-content">
              <div
                class="message-text"
                v-html="renderMessageContent(message.content)"
                v-if="message.messageType === 1"
              ></div>
              <template v-else-if="message.messageType === 2">
                <img
                  :src="message.content"
                  alt="图片"
                  class="message-image"
                  @click="handleImagePreview(message.content)"
                />
              </template>
              <!-- <template v-else-if="message.messageType === 3">
                <video
                  :src="message.content"
                  alt="视频"
                  class="message-video"
                ></video>
              </template> -->
              <div class="message-time">
                {{ getTimePart(message.createTime) }}
                <span v-if="message.status === 'sending'" class="status-icon">
                  <i class="el-icon-loading"></i>
                </span>
                <span
                  v-else-if="message.status === 'delivered'"
                  class="status-icon"
                >
                  <i class="el-icon-check"></i>
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="no-content" v-else>
          <i class="el-icon-chat-dot-round"></i>
          <p>暂无对话消息</p>
        </div>
      </el-scrollbar>
      <!-- 输入区域 -->
      <div class="chat-input-area" v-if="currentUser">
        <!-- <div class="chat-input-area"> -->
        <!-- 工具栏 -->
        <div class="toolbar">
          <div class="emoji-container">
            <img
              src="@/assets/biaoqing.png"
              class="emoji-trigger"
              @click="toggleEmojiPanel()"
            />
            <!-- 表情面板 -->
            <div v-if="showEmojiPanel" class="emoji-panel">
              <div
                v-for="emoji in emojis"
                :key="emoji.symbol"
                class="emoji-item"
                @click="insertEmoji(emoji)"
                :title="emoji.name"
              >
                {{ emoji.symbol }}
              </div>
            </div>
          </div>
          <!-- <el-upload
            class="file-upload"
            style="width: 32px; height: 32px"
            action="/api/upload"
            :show-file-list="false"
            :before-upload="beforeFileUpload"
            :on-success="handleFileUploadSuccess"
          >
            <el-button
              type="text"
              style="font-size: 27px"
              icon="el-icon-folder-opened"
              title="发送文件"
            ></el-button>
          </el-upload> -->

          <!-- <el-upload
            class="image-upload"
            style="width: 32px; height: 32px"
            action="/api/upload"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :on-success="handleImageUploadSuccess"
            accept="image/*"
          >
            <el-button
              type="text"
              style="font-size: 27px"
              icon="el-icon-picture"
              title="发送图片"
            ></el-button>
          </el-upload> -->
        </div>
        <!-- 输入区域 -->
        <div class="chat-input">
          <el-input
            v-model="newMessage.content"
            placeholder="请输入聊天内容"
            type="textarea"
            :rows="3"
            resize="none"
            class="message-input"
            @keydown.enter.native="handleKeydown"
          ></el-input>
          <el-button
            type="primary"
            @click="sendMessage"
            class="send-button"
            :disabled="!newMessage.content.trim()"
            >发送</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  reqSendMessage,
  reqGetConversations,
  reqGetHistory,
  reqReadMessage,
  reqDeleteMessage,
  reqGetUnreadCount,
  reqReadConversation,
  reqSearchConversation,
  reqOnlineUsers,
} from "@/api";
import websocket from "@/utils/websocket";
import { emojis } from "@/assets/js/biaoqing.js";

export default {
  name: "PrivateMessage",
  data() {
    return {
      currentUser: null, // 当前聊天的人
      loginUser: null,
      messages: [],
      messageForm: [], // 会话列表
      onlineUsers: [], // 在线用户列表
      newMessage: {
        receiverId: "",
        content: "",
        fileUrl: "", //文件路径
        messageType: "", //1:文字 2:图片 3:文件 4.语音
      },
      searchUserName: "",
      isWebSocketInitialized: false, // WebSocket初始化标志
      // 表情列表
      showEmojiPanel: false,
      emojis: emojis,
      // 用于记录用户是否手动向上滚动
      _userScrolledUp: false,
      forceScroll: false,
      shouldScrollToBottom: false,
    };
  },
  computed: {
    userId() {
      return (
        this.$store.state.user.userForm.userId ||
        JSON.parse(sessionStorage.getItem("user")).userId
      );
    },
  },
  watch: {
    userId(newId) {
      if (newId) {
        websocket.Close();
        this.connectWebSocket();
      }
    },
    // 监听当前用户ID变化
    currentUser(newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        // 用户切换时，标记需要滚动到底部
        this._userScrolledUp = false;
        this.shouldScrollToBottom = true;

        // 在下一个tick执行滚动
        this.$nextTick(() => {
          if (this.shouldScrollToBottom) {
            this.scrollToBottom();
            this.shouldScrollToBottom = false;
          }
        });
      }
    },
    messages(newMessages) {
      if (newMessages.length > 0) {
        this.messages = newMessages;
        console.log("newMessages:", newMessages);
        this.forceScrollToBottom();
      }
    },
  },
  mounted() {
    this.initWebSocketListener(); // 初始化WebSocket监听
    document.addEventListener("click", this.handleClickOutside);

    // 添加鼠标滚轮事件监听
    this.$nextTick(() => {
      const container =
        this.$refs.messageContainer?.$el || this.$refs.messageContainer;
      if (container) {
        container.addEventListener("wheel", this.handleWheelEvent, {
          passive: true,
        });
      }
    });
  },

  created() {
    // 确保在使用userId时，userId被创建出来了
    // console.log("用户ID：", this.userId);
    if (this.userId) {
      this.loginUser = JSON.parse(sessionStorage.getItem("user"));
      this.connectWebSocket(this.userId);
      this.reqGetConversations();
      this.reqOnlineUser(); // 查询在线用户

      // 保存用户ID到sessionStorage，用于刷新后重连
      sessionStorage.setItem("ws_userId", this.userId);
    } else {
      console.warn("未获取到有效userId");
    }
  },
  beforeDestroy() {
    // 组件销毁时关闭WebSocket连接
    websocket.Close();
    sessionStorage.removeItem("ws_userId");
    document.removeEventListener("click", this.handleClickOutside);

    // 移除鼠标滚轮事件监听
    const container =
      this.$refs.messageContainer?.$el || this.$refs.messageContainer;
    if (container) {
      container.removeEventListener("wheel", this.handleWheelEvent);
    }
  },
  methods: {
    // 强制滚动到底部
    forceScrollToBottom() {
      this.forceScroll = true;
      this.scrollToBottom();
      // 重置强制滚动标志
      this.$nextTick(() => {
        this.forceScroll = false;
      });
    },
    PushUserProfile() {
      this.$router.push({
        name: "player",
        params: {
          userId: this.$store.state.userId,
          competitionId: this.$route.params.competitionId,
        },
      });
    },
    handleClickOutside(event) {
      const isEmojiPanel = event.target.closest(".emoji-panel");
      const isEmojiImage = event.target.closest(".emoji-trigger");
      if (!isEmojiPanel && !isEmojiImage) {
        this.showEmojiPanel = false;
      }
    },
    async reqOnlineUser() {
      const res = await reqOnlineUsers();
      if (res.code === 200) {
        this.onlineUsers = res.data;
      } else {
        console.error("获取在线用户列表失败");
      }
    },
    getTimePart(dateTime) {
      if (!dateTime) return "";
      const parts = dateTime.split(/[\sT]/);
      return parts.length > 1 ? parts[1] : dateTime;
    },
    // 渲染消息内容，支持表情渲染
    renderMessageContent(content) {
      // 简单的表情渲染
      return content;
    },

    async fetchMessages(userId) {
      try {
        if (!userId) {
          this.reqGetConversations();
          return;
        }
        const res = await reqGetHistory({ otherUserId: userId });
        if (res.code === 200) {
          this.messages = res.data;
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else {
          console.error("获取聊天记录失败:", res.message);
          this.$message.error(`获取聊天记录失败: ${res.message}`);
        }
      } catch (error) {
        console.error("请求异常详情:", error);

        // 更详细的错误信息
        if (error.response) {
          // 服务器响应了错误状态码
          console.error("响应状态:", error.response.status);
          console.error("响应数据:", error.response.data);
          console.error("响应头:", error.response.headers);

          this.$message.error(
            `服务器错误 (${error.response.status}): ${
              error.response.data?.message || "请稍后重试"
            }`
          );
        } else if (error.request) {
          // 请求发送了但没有收到响应
          console.error("请求信息:", error.request);
          this.$message.error("网络错误，请检查连接");
        } else {
          // 其他错误
          console.error("错误信息:", error.message);
          this.$message.error(`请求失败: ${error.message}`);
        }
      }
    },
    // 处理键盘事件
    handleKeydown(event) {
      if (event.key === "Enter") {
        if (event.ctrlKey || event.metaKey) {
          // Ctrl+Enter 换行
          // this.newMessage.content += "\n";
        } else {
          // Enter 发送
          event.preventDefault(); // 阻止默认的换行行为
          this.sendMessage();
        }
      }
    },

    sendMessage() {
      if (!this.newMessage.content.trim()) {
        this.$message.warning("请输入聊天内容");
        return;
      }

      if (!this.currentUser) {
        this.$message.warning("请选择聊天对象");
        return;
      }

      const message = {
        senderId: this.loginUser.userId,
        receiverId: this.currentUser.receiveUser,
        content: this.newMessage.content.trim(),
        createTime: new Date().toISOString(),
      };
      console.log("发送消息:", message);

      // 1. 通过WebSocket发送消息
      this.sendWebSocketMessage(message);

      message.id = Date.now();
      message.status = "sending";
      // 2. 添加到本地消息列表（临时消息）
      this.messages.push({
        ...message,
      });
      // 4. 清空输入框
      this.newMessage.content = "";
      // this.scrollToBottom();
      this.$nextTick(() => {
        setTimeout(() => {
          this.forceScroll = true;
          this.scrollToBottom();
          this.forceScroll = false;
        }, 100);
      });

      // 5. 发送到服务器保存
      reqSendMessage({
        receiverId: this.currentUser.receiveUser,
        content: message.content,
        messageType: 1,
        fileUrl: "",
      }).then((res) => {
        if (res.code === 200) {
          // 更新消息状态为已送达
          const tempId = message.id;
          const index = this.messages.findIndex((m) => m.id === tempId);
          if (index !== -1) {
            this.$set(this.messages, index, {
              ...this.messages[index],
              id: res.data.id, // 使用服务器返回的真实ID
              status: "delivered",
              createTime: res.data.createTime,
              messageType: res.data.messageType,
            });
          }
        } else {
          console.error("消息发送失败");

          // 更新消息状态为发送失败
          const tempId = message.id;
          const index = this.messages.findIndex((m) => m.id === tempId);
          if (index !== -1) {
            this.$set(this.messages, index, {
              ...this.messages[index],
              status: "failed",
            });
          }
        }
      });
      this.$nextTick(() => {
        this.reqGetConversations();
        this.chooseUser(this.currentUser);
      });
    },

    // 处理鼠标滚轮事件
    handleWheelEvent(event) {
      const container =
        this.$refs.messageContainer?.$el || this.$refs.messageContainer;
      if (!container) return;

      // 计算距离底部的距离
      const distanceToBottom =
        container.scrollHeight - container.scrollTop - container.clientHeight;

      // 如果用户向上滚动且远离底部，标记为用户手动滚动
      if (event.deltaY < 0 && distanceToBottom > 50) {
        this._userScrolledUp = true;
      }
      // 如果用户滚动到接近底部，重置标记
      else if (distanceToBottom <= 50) {
        this._userScrolledUp = false;
      }
    },

    // 滚动到底部函数
    scrollToBottom() {
      // 只有在用户没有手动向上滚动或者强制滚动时才执行
      if (this._userScrolledUp && !this.forceScroll) {
        return;
      }
      this.$nextTick(() => {
        try {
          const scrollbar = this.$refs.messageContainer;
          if (!scrollbar) {
            console.warn("滚动失败，未找到滚动元素");
            return;
          }
          const wrap = scrollbar.wrap;
          if (!wrap) {
            console.warn("滚动失败，未找到滚动元素");
            return;
          }
          // console.log("滚动容器信息:", {
          //   scrollHeight: wrap.scrollHeight,
          //   clientHeight: wrap.clientHeight,
          //   scrollTop: wrap.scrollTop,
          // });
          // 使用 Element UI 的 scrollTo 方法
          wrap.scrollTop = wrap.scrollHeight;
          setTimeout(() => {
            wrap.scrollTop = wrap.scrollHeight;
          }, 50);
        } catch (error) {
          console.error("滚动到底部失败", error);
          // 出错时使用最基础的滚动方式
          this.fallbackScroll();
        }
      });
    },
    // 回退滚动方法
    fallbackScroll() {
      try {
        // 尝试直接查找 Element UI 的滚动包装器
        const wrap = document.querySelector(".el-scrollbar__wrap");
        if (wrap && wrap.scrollHeight > wrap.clientHeight) {
          wrap.scrollTop = wrap.scrollHeight;
          console.log("备用方案滚动成功");
        }
      } catch (error) {
        console.error("备用方案滚动失败", error);
      }
    },

    async chooseUser(form) {
      try {
        this.currentUser = form;
        this.messages = [];

        this._userScrolledUp = false;
        this.forceScroll = false;
        await this.fetchMessages(form.receiveUser);
        // 确保滚动到底部
        this.$nextTick(() => {
          setTimeout(() => {
            this.scrollToBottom();
          }, 100);
        });
        // 标记该会话为已读
        const res = await reqReadConversation({
          otherUserId: form.receiveUser,
        });
        if (res.data) {
          form.status = "已读";
        }
        // 更新会话列表中的未读计数
        const conversation = this.messageForm.find(
          (conv) => conv.id === form.id
        );
        if (conversation) {
          conversation.unreadCountUser2 = 0;
        }
      } catch (e) {
        console.log("用户选择失败:", e);
      } finally {
        setTimeout(() => {
          this.forceScroll = false;
        }, 1000);
      }
    },

    //更新表情包列表
    toggleEmojiPanel() {
      this.showEmojiPanel = !this.showEmojiPanel;
    },

    //插入表情
    insertEmoji(emoji) {
      this.newMessage.content += emoji.symbol;
      this.showEmojiPanel = false;
    },

    // WebSocket相关方法
    async connectWebSocket(userId) {
      try {
        await new Promise((resolve) => {
          websocket.Init(userId);
          websocket.getWebSocket().onopen = () => {
            console.log("WebSocket连接成功");
            resolve();
          };
        });
      } catch (e) {
        console.error("WebSocket连接失败:", e);
      }
    },

    initWebSocketListener() {
      if (this.isWebSocketInitialized) return;

      websocket.setMessageCallback((data) => {
        this.handleIncomingMessage(data);
      });

      this.isWebSocketInitialized = true;
    },

    handleIncomingMessage(data) {
      try {
        const message = JSON.parse(data);
        console.log("收到新消息:", message);

        // 1. 如果是当前会话的消息，直接添加到列表
        if (
          this.currentUser &&
          (message.senderId === this.currentUser.sendUser ||
            message.receiverId === this.currentUser.receiveUser)
        ) {
          this.messages.push({
            ...message,
            status: "delivered",
          });
          this.scrollToBottom();
        }

        // 2. 更新会话列表
        this.updateConversationList(message);
      } catch (e) {
        console.error("消息解析错误:", e);
      }
    },

    updateConversationList(message) {
      const receiveId = message.receiverId;

      // 查找是否已存在该会话
      const conversationIndex = this.messageForm.findIndex(
        (conv) => conv.receiveUser === receiveId
      );

      if (conversationIndex !== -1) {
        // 更新现有会话
        const updatedConversations = [...this.messageForm];
        updatedConversations[conversationIndex] = {
          ...updatedConversations[conversationIndex],
          lastMessage: message.content,
          lastMessageTime: message.createTime,
          unreadCountUser2:
            this.currentUser?.receiveUser === receiveId
              ? 0
              : updatedConversations[conversationIndex].unreadCountUser2 + 1,
        };

        // 置顶会话
        const [updated] = updatedConversations.splice(conversationIndex, 1);
        this.messageForm = [updated, ...updatedConversations];
      } else {
        // 创建新会话（需要获取用户信息）
        // this.addNewConversation(senderId, message);
        return;
      }
    },

    // async addNewConversation(userId, message) {
    //   // 这里需要调用API获取用户信息
    //   // 伪代码：const userInfo = await getUserById(userId);

    //   // 创建新会话项
    //   const newConversation = {
    //     sendUser: {
    //       userId: userId,
    //       userName: "新用户", // 从API获取
    //       avatar: "default-avatar.jpg", // 从API获取
    //     },
    //     lastMessage: message.content,
    //     lastMessageTime: message.createTime,
    //     unreadCountUser2: 1,
    //     isOnline: true,
    //   };

    //   // 添加新会话并置顶
    //   this.messageForm = [newConversation, ...this.messageForm];
    // },

    sendWebSocketMessage(message) {
      if (
        !websocket.getWebSocket() ||
        websocket.getWebSocket().readyState !== WebSocket.OPEN
      ) {
        console.warn("WebSocket连接未就绪，尝试重连");
        this.connectWebSocket(this.userId);

        // 延迟发送
        setTimeout(() => {
          websocket.Send(message);
        }, 500);
        return;
      }

      websocket.Send(message);
    },

    // 获取会话列表
    async reqGetConversations() {
      try {
        const res = await reqGetConversations();
        if (res.code == 200) {
          this.messageForm = res.data;
          this.messageForm.forEach((item) => {
            if (item.user1Id === this.loginUser.userId) {
              item.receiveUser = item.user2Id;
              item.sendUser = item.user1Id;
            } else {
              item.receiveUser = item.user1Id;
              item.sendUser = item.user2Id;
            }
          });
        } else {
          console.error("获取会话列表失败:", res.message);
        }
      } catch (e) {
        console.error("获取会话列表异常:", e);
      }
    },

    // 搜索用户
    async searchUserForForm() {
      if (!this.searchUserName.trim()) {
        this.reqGetConversations();
        return;
      }
      const res = await reqSearchConversation(this.searchUserName);
      if (res.code == 200) {
        this.messageForm = res.data;
        this.messageForm.forEach((item) => {
          if (item.user1Id === this.loginUser.userId) {
            item.receiveUser = item.user2Id;
            item.sendUser = item.user1Id;
          } else {
            item.receiveUser = item.user1Id;
            item.sendUser = item.user2Id;
          }
        });
      } else {
        console.error("获取会话列表失败:", res.message);
        this.messageForm = [];
      }
    },
    beforeImageUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error("只能上传图片");
      }
      if (!isLt5M) {
        this.$message.error("图片大小不能超过5M");
      }
      return isImage && isLt5M;
    },

    handleImageUploadSuccess(response) {
      if (response.code === 200) {
        this.sendMediaMessage(response.data, 2);
      }
    },
    beforeFileUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过10M!");
      }
      return isLt10M;
    },

    handleFileUploadSuccess(response) {
      if (response.code === 200) {
        this.sendMediaMessage(response.data, 3);
      }
    },

    sendMediaMessage(fileUrl, messageType) {
      if (!this.currentUser) return;
      const message = {
        senderId: this.loginUser.userId,
        receiverId: this.currentUser.receiveUser,
        content: fileUrl,
        messageType: messageType,
      };
      this.sendWebSocketMessage(message);
      message.id = Date.now();
      message.status = "sending";
      this.messages.push(message);

      reqSendMessage({
        receiverId: this.currentUser.receiveUser,
        content: fileUrl,
        messageType: messageType,
        // fileUrl:fileUrl
      }).then((res) => {
        if (res.code === 200) {
          const index = this.messages.findIndex((m) => m.id === message.id);
          if (index !== -1) {
            this.messages[index].id = res.data.id;
            this.messages[index].status = "delivered";
          }
        }
      });
    },
    handleImagePreview(imageUrl) {
      this.$preview.open(imageUrl);
    },
  },
};
</script>

<style lang="scss" scoped>
// 主题变量
$primary-color: #409eff;
$primary-light: #ecf5ff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$info-color: #909399;

$bg-color: #f5f7fa;
$border-color: #e4e7ed;
$text-primary: #303133;
$text-regular: #606266;
$text-secondary: #909399;
$text-placeholder: #c0c4cc;

$radius-sm: 4px;
$radius-md: 8px;
$radius-lg: 12px;
$radius-xl: 16px;
$radius-circle: 50%;

$shadow-light: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
$shadow-medium: 0 2px 16px 0 rgba(0, 0, 0, 0.12);

.chat-container {
  display: flex;
  height: calc(100vh - 61px);
  background: $bg-color;
  border-top: 1px solid #e4e7ed;
}

/* 用户列表容器 */
.user-list-scroll {
  flex: 1;

  .user-list {
    padding: 8px 0;
  }
}

/* 用户项样式 */
.user-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  margin: 0 12px 8px 12px;
  height: 100px;
  cursor: pointer;
  border-radius: 16px;
  transition: all 0.3s ease;
  background: white;
  border: 1px solid transparent;
  position: relative;
  min-height: 72px;

  &:hover {
    background: linear-gradient(135deg, #f8faff 0%, #f0f4ff 100%);
    border-color: #e1e8ff;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(67, 97, 238, 0.15);
  }

  &.active {
    background-color: #ecf5ff; /* 激活状态背景色 */
    border-right: 3px solid #409eff; /* 激活状态边框 */

    .user-details {
      .user-name {
        // color: white;
        font-weight: 600;
      }
    }
  }
}

/* 头像区域 */
.user-avatar-wrapper {
  position: relative;
  margin-right: 16px;
  flex-shrink: 0;

  .user-avatar {
    width: 52px;
    height: 52px;
    border-radius: 14px;
    object-fit: cover;
    border: 3px solid white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
  }

  .online-indicator {
    position: absolute;
    bottom: 2px;
    right: 2px;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    border: 2px solid white;
    background: #dcdfe6;
    transition: all 0.3s ease;
    z-index: 2;

    &.online {
      background: #10b981;
      box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
    }
  }

  .message-badge {
    position: absolute;
    bottom: -30px;

    ::v-deep .el-badge__content {
      background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
      border: 2px solid white;
      font-weight: 600;
      font-size: 10px;
      min-width: 18px;
      height: 18px;
      line-height: 14px;
      box-shadow: 0 2px 6px rgba(255, 107, 107, 0.3);
    }
  }
}

/* 用户信息区域 */
.user-details {
  flex: 1;
  min-width: 0;
  position: absolute;
  left: 110px;
  padding-top: 15px;
  width: 65%;
  display: flex;
  flex-direction: column;
  gap: 6px;

  .user-name {
    font-weight: 600;
    font-size: 15px;
    text-align: left;
    color: #1f2937;
    line-height: 1.2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: color 0.3s ease;
  }

  .user-last-message {
    font-size: 12px;
    color: #6b7280;
    text-align: left;
    line-height: 1.3;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: color 0.3s ease;
  }
  .user-last-time {
    font-size: 11px;
    color: #9ca3af;
    text-align: right;
    font-weight: 500;
    flex-shrink: 0;
    transition: color 0.3s ease;
  }

  .user-status {
    font-size: 11px;
    color: #10b981;
    font-weight: 600;
    padding: 2px 6px;
    background: rgba(16, 185, 129, 0.1);
    border-radius: 8px;
    flex-shrink: 0;
  }
}

/* 空状态样式 */
.no-users {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #9ca3af;
  text-align: center;

  i {
    font-size: 64px;
    margin-bottom: 16px;
    color: #e5e7eb;
    opacity: 0.7;
  }

  p {
    margin: 0;
    font-size: 14px;
    font-weight: 500;
  }
}

/* 搜索框样式 */
.search-wrapper {
  padding: 20px;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #f3f4f6;

  .search-input {
    ::v-deep .el-input__inner {
      border-radius: 12px;
      padding-left: 40px;
      border: 1px solid #e5e7eb;
      background: #f9fafb;
      transition: all 0.3s ease;

      &:focus {
        border-color: #4361ee;
        background: white;
        box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
      }
    }

    .el-icon-search {
      color: #6b7280;
      font-size: 16px;
    }
  }
}

/* 左侧边栏整体样式 */
.left-side {
  width: 360px;
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
  border-right: 1px solid #e2e8f0;
  display: flex;
  flex-direction: column;

  .user-list-scroll {
    ::v-deep .el-scrollbar__wrap {
      scrollbar-width: thin;

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 2px;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .left-side {
    width: 100%;

    .user-item {
      margin: 0 8px 6px 8px;
      padding: 12px 16px;

      .user-avatar-wrapper .user-avatar {
        width: 44px;
        height: 44px;
      }
    }
  }
}
/* 右侧区域 */
.right-side {
  flex: 1;
  display: flex;
  height: calc(100vh - 61px);
  min-height: 0;
  overflow: hidden;
  flex-direction: column;
  background: white;

  .chat-header {
    padding: 16px 24px;
    flex-shrink: 0;
    border-bottom: 1px solid $border-color;
    background: white;

    &.empty {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;

      .empty-chat {
        text-align: center;
        color: $text-secondary;

        i {
          font-size: 64px;
          margin-bottom: 16px;
          color: $border-color;
        }

        p {
          margin: 0;
          font-size: 16px;
        }
      }
    }

    .header-user {
      display: flex;
      align-items: center;

      .header-avatar {
        position: relative;
        margin-right: 12px;

        img {
          width: 40px;
          height: 40px;
          border-radius: $radius-circle;
          object-fit: cover;
        }

        .online-dot {
          position: absolute;
          bottom: 2px;
          right: 2px;
          width: 8px;
          height: 8px;
          background-color: $success-color;
          border-radius: $radius-circle;
          border: 2px solid white;
        }
      }

      .header-info {
        .header-name {
          font-weight: 600;
          color: $text-primary;
          font-size: 16px;
          margin-bottom: 2px;
        }

        .header-status {
          font-size: 12px;
          color: $text-secondary;
        }
      }
    }
  }

  .chat-messages {
    flex: 1;
    height: 0px; /* 关键 */
    min-height: 0;
    // overflow-y: auto;
    padding: 24px;
    background: #fafafa;
    // Element UI 滚动条样式
    ::v-deep .el-scrollbar {
      height: 100%;

      .el-scrollbar__wrap {
        overflow-y: auto;
        max-height: 100%;
      }

      .el-scrollbar__view {
        min-height: 100%;
      }
    }
    .messages-wrapper {
      min-height: min-content;
      .message-box {
        display: flex;
        margin-bottom: 20px;
        max-width: 70%;

        .avatar {
          flex-shrink: 0;
          margin-right: 12px;

          img {
            width: 36px;
            height: 36px;
            border-radius: $radius-circle;
            object-fit: cover;
          }
        }

        .message-content {
          .message-text {
            padding: 12px 16px;
            border-radius: $radius-xl;
            background: white;
            box-shadow: $shadow-light;
            line-height: 1.5;
            font-size: 14px;
            word-wrap: break-word;
          }

          .message-image {
            max-width: 200px;
            max-height: 200px;
            border-radius: $radius-md;
            cursor: pointer;
            transition: transform 0.2s ease;

            &:hover {
              transform: scale(1.02);
            }
          }

          .message-time {
            font-size: 12px;
            color: $text-secondary;
            margin-top: 6px;
            display: flex;
            align-items: center;

            .status-icon {
              margin-left: 4px;
              font-size: 12px;

              .el-icon-check {
                color: $success-color;
              }

              .el-icon-loading {
                color: $text-placeholder;
              }
            }
          }
        }

        &.own-message {
          margin-left: auto;
          flex-direction: row-reverse;

          .avatar {
            margin-right: 0;
            margin-left: 12px;
          }

          .message-content {
            .message-text {
              background: $primary-light;
              color: $primary-color;
              border-bottom-right-radius: $radius-sm;
            }

            .message-time {
              justify-content: flex-end;
            }
          }
        }

        &.other-message {
          .message-content .message-text {
            border-bottom-left-radius: $radius-sm;
          }
        }
      }
    }

    .no-content {
      margin-top: 20%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
      height: 100%;
      i {
        font-size: 100px;
        color: #999;
        margin-bottom: 20px;
      }
      p {
        font-size: 36px;
        color: #999;
        margin: 0;
      }
    }
  }

  .chat-input-area {
    border-top: 1px solid $border-color;
    background: white;

    .toolbar {
      height: 40px;
      display: flex;
      align-items: center;
      padding-left: 16px;
      gap: 16px;

      .emoji-container {
        width: 32px;
        height: 32px;
        padding-top: 21px;
        position: relative;
        display: flex;
        .emoji-trigger {
          width: 32px;
          height: 32px;
        }
        .el-button {
          line-height: 32px;
          color: $text-secondary;
          &:hover,
          &.active {
            color: $primary-color;
          }
        }
        .emoji-panel {
          position: absolute;
          bottom: 100%;
          left: 0;
          width: 300px;
          height: 300px;
          display: flex;
          flex-wrap: wrap;
          background: white;
          border: 1px solid $border-color;
          border-radius: $radius-md;
          box-shadow: $shadow-medium;
          overflow-y: auto;
          scrollbar-width: 0px;
          z-index: 1000;
          // &::-webkit-scrollbar {
          //   width: 0px;
          //   display: none;
          //   height: 0px;
          // }
          &:hover {
            color: $text-regular;
          }
          .emoji-item {
            height: 32px;
            width: 30px;
            font-size: 20px;
            cursor: pointer;
            border: 1px solid $border-color;
            transition: background-color 0.2s ease;

            &:hover {
              background-color: #f5f5f5;
            }
          }
        }
      }
    }

    .chat-input {
      padding: 16px;
      display: flex;
      gap: 12px;

      .message-input {
        flex: 1;

        ::v-deep .el-textarea__inner {
          border: 1px solid $border-color;
          border-radius: $radius-md;
          padding: 12px 16px;
          resize: none;
          font-size: 14px;
          line-height: 1.5;
          transition: border-color 0.3s ease;

          &:focus {
            border-color: $primary-color;
          }
        }
      }

      .send-button {
        align-self: flex-end;
        padding: 10px 24px;
        border-radius: $radius-md;

        &:disabled {
          opacity: 0.6;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .chat-container {
    flex-direction: column;
  }

  .left-side {
    width: 100%;
    height: 40%;
  }

  .right-side {
    height: 60%;
  }

  .message-box {
    max-width: 85% !important;
  }

  .emoji-panel {
    width: 280px !important;
  }
}
</style>
